//
//  QRCodeScanningView.swift
//  swift_wobo
//
//  Created by yuxin on 2018/11/17.
//  Copyright © 2018 wuxiantianli. All rights reserved.
//

import UIKit

let qrcodeSize = CGSize(width: 218.0, height: 170.0)
let barcodeSize = CGSize(width: 248.0, height: 124.0)

enum ScanningViewType : String {
    case QR = "qrcode"
    case BAR = "barcode"
}

class QRCodeScanningView: UIView {
    
    var scanViewType : ScanningViewType? {
        didSet{
            
            if scanViewType == ScanningViewType.QR {
                bounds = CGRect(origin: CGPoint.zero, size: qrcodeSize)
                scanImageView.image = UIImage(named: "qrcode_scanline_qrcode")
                
            } else if scanViewType == ScanningViewType.BAR {
                bounds = CGRect(origin: CGPoint.zero, size: barcodeSize)
                scanImageView.image = UIImage(named: "qrcode_scanline_qrcode")
            }
            
            borderImageView.frame = bounds
            scanImageView.frame = bounds
            scanImageView.frame.origin.y = -bounds.size.height
            
            self.layer.removeAllAnimations()
            startAnimation()
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI() {
        addSubview(borderImageView)
        addSubview(scanImageView)
        self.layer.masksToBounds = true
        scanViewType = ScanningViewType.QR
    }
    
    private func startAnimation() {
    
        let dutation : TimeInterval = (scanViewType == ScanningViewType.QR) ? 2.0 : 1.5
        UIView.animate(withDuration: dutation, animations: {
            UIView.setAnimationRepeatCount(Float(CGFloat.greatestFiniteMagnitude))
            self.scanImageView.frame.origin.y = self.bounds.size.height * 0.6
        })
        
    }
    
    //MARK: - lazy
    private lazy var borderImageView : UIImageView = {
        let iv = UIImageView(image: UIImage(named: "qrcode_border"))
        return iv
    }()
    
    private lazy var scanImageView : UIImageView = {
        let iv = UIImageView(image: UIImage(named: "qrcode_scanline_qrcode"))
        return iv
    }()
    
    
}
